package com.ay.shardingshere.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;
import java.util.Date;

/**
 * @Author: ay
 * @Date: 2021/6/29
 * @Description:
 **/
@Slf4j
public class TableShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        System.out.println("table PreciseShardingAlgorithm ");
        // 真实节点
        collection.stream().forEach((item) -> {
            log.info("actual node table:{}", item);
        });

        log.info("logic table name:{},rout column:{}", preciseShardingValue.getLogicTableName(), preciseShardingValue.getColumnName());

        //精确分片
        log.info("column value:{}", preciseShardingValue.getValue());

        String tb_name = preciseShardingValue.getLogicTableName() + "_";

        // 根据当前日期 来 分库分表
        Date date = preciseShardingValue.getValue();
        String year = String.format("%tY", date);
        String month = String.format("%tm", date);
        String day = String.format("%td", date);

        // 选择表
        tb_name = tb_name + year + "_" + month;
        log.info("tb_name:{}", tb_name);

        for (String each : collection) {
            log.info("t_order_{}", each);
            if (each.equals(tb_name)) {
                return each;
            }
        }
        throw new IllegalArgumentException("系统配置异常");
    }
}
